package com.thread.threadfirst.marvel.zuul;


import java.util.Random;

public class EncryptUtil {



    /**
     * @param sourceString
     * @param password
     * @return 密文
     */
    public static String encrypt(String sourceString, String password) {
        String val = "";
        Random random = new Random();
        for (int i = 0; i < 12; i++) {
            val += random.nextInt(10);
        }

        char[] p = password.toCharArray(); // 字符串转字符数组
        int n = p.length; // 密码长度
        String d = new StringBuilder().append(val).append(sourceString).toString();
        char[] c = d.toCharArray();
        int m = c.length; // 字符串长度

        for (int k = 0; k < m; k++) {
            int mima = c[k] + p[k / n]; // 加密
            c[k] = (char) mima;
        }

        return new String(c);
    }

    /**
     *
     * @param sourceString
     * @param password
     * @return 明文
     */
    public static String decrypt(String sourceString, String password) {
        char[] p = password.toCharArray(); // 字符串转字符数组
        int n = p.length; // 密码长度
        char[] c = sourceString.toCharArray();
        int m = c.length; // 字符串长度
        for (int k = 0; k < m; k++) {
            int mima = c[k] - p[k / n]; // 解密
            c[k] = (char) mima;
        }
        String str="";
        for(int i = 12; i<c.length; i++) {
            str += c[i];
        }
        return new String(String.valueOf(str));
    }

    /*
     * 使用例子
     */
    public static void main(String arg[]) {
        String wen = "1222";
        String pass = "225299699";
//        byte[] sb = wen.getBytes();
        System.out.println(encrypt(wen, pass));

        System.out.println(decrypt(encrypt(wen,pass),pass));


    }
}
